/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-04-16
 * Time:10:41
 */

public class MyLinkedList {
    public ListNode head;
    public ListNode last;

    public void display() {
        ListNode cur = this.head;
        while (cur != null) {
            System.out.println(cur.value);
            cur = cur.next;
        }
    }

    public int size() {
        ListNode cur = this.head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    //头插
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
            this.last = node;
            return;
        }
        node.next = this.head;
        this.head.prev = node;
        this.head = node;
    }

    //尾插
    public void addList(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
            this.last = node;
            return;
        }
        this.last.next = node;
        node.prev = this.last;
        this.last = node;
    }

    //***删除第一次出现key的节点***
    public void remove(int key) {
        ListNode cur = this.head;
        while (cur != null) {
            if (cur.value == key) {
                if (cur == this.head) {
                    if (this.last == this.head) {
                        this.head = null;
                        this.last = null;
                        return;
                    }
                    cur.next.prev = null;
                    this.head = cur.next;
                    return;
                } else if (cur == this.last) {
                    this.last = this.last.prev;
                    cur.prev.next = null;
                    return;
                }
                cur.prev.next = cur.next;
                cur.next.prev = cur.prev;
            }
            cur = cur.next;
        }
    }

    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index, int data) {

        if (index < 0 || index > this.size()) {
            System.out.println("坐标非法");
            return false;
        } else if (index == 0) {
            this.addFirst(data);
            return true;
        } else if (index == this.size()) {
            this.addList(data);
            return true;
        } else {
            ListNode cur = this.head;
            ListNode node = new ListNode(data);
            while (index != 0) {
                index--;
                cur = cur.next;
            }
            cur.prev.next = node;
            node.prev = cur.prev;
            node.next = cur;
            cur.prev = node;
            return true;
        }
    }
    public void clear(){
        while(this.head!=null){
            ListNode next=this.head.next;
            this.head.prev=null;
            this.head.next=null;
            this.head=next;
        }
        this.last=null;
    }
}
